搜索插入位置

题目描述给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
你可以假设数组中无重复元素。

示例 1:
输入: [1,3,5,6], 5
输出: 2

示例 2:
输入: [1,3,5,6], 2
输出: 1

示例 3:
输入: [1,3,5,6], 7
输出: 4

示例 4:
输入: [1,3,5,6], 0
输出: 0

二分法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Solution {
public int searchInsert(int[] nums, int target) {
if(nums == null || nums.length == 0) return 0;
int i = 0, j = nums.length - 1;
while(i <= j) {
int m = i + (j - i) /2;
if(nums[m] == target) {
return m;
} else if(nums[m] > target) {
j = m -1;
} else {
i= m + 1;
}
}
return i;
}
}

复杂度分析

  • 时间复杂度:O(logn),其中 n 为数组的长度。二分查找所需的时间复杂度为 O(logn)。

  • 空间复杂度:O(1)。我们只需要常数空间存放若干变量。